<template>
  <div class="nav-link">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="分组">
          <el-select 
            v-model="searchForm.groupId" 
            placeholder="请选择分组"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="group in groups"
              :key="group.id"
              :label="group.groupName"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList">查询</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column label="图标" width="70" align="center">
          <template #default="{ row }">
            <span v-if="row.icon" v-html="row.icon" class="svg-icon"></span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="链接标题" />
        <el-table-column prop="url" label="链接地址" show-overflow-tooltip />
        <el-table-column prop="linkDesc" label="链接描述" show-overflow-tooltip />
        <el-table-column label="所属分组" min-width="120">
          <template #default="{ row }">
            <el-select 
              v-model="row.groupId" 
              @change="(val) => handleGroupChange(row, val)"
              style="width: 100%"
            >
              <el-option
                v-for="group in groups"
                :key="group.id"
                :label="group.groupName"
                :value="group.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="sortNo" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="name">
          <el-input v-model="form.name" placeholder="请输入链接标题" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input
            v-model="form.icon"
            type="textarea"
            :rows="3"
            placeholder="请输入SVG图标代码"
          />
          <div class="icon-preview" v-if="form.icon">
            <span>图标预览：</span>
            <span v-html="form.icon" class="svg-icon"></span>
          </div>
        </el-form-item>
        <el-form-item label="地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="分组" prop="groupId">
          <el-select 
            v-model="form.groupId" 
            placeholder="请选择分组"
            style="width: 100%"
          >
            <el-option
              v-for="group in groups"
              :key="group.id"
              :label="group.groupName"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="linkDesc">
          <el-input v-model="form.linkDesc" type="textarea" placeholder="请输入链接描述" />
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input-number v-model="form.sortNo" :min="0" :max="99" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status" @change="handleStatusChange">
            <el-radio :value="1">启用</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { request } from '@/utils/request'
import { validateSvg } from '@/utils/svgValidator'
import { sanitizeSvg } from '@/utils/xssFilter'

// 搜索表单
const searchForm = reactive({
  groupId: undefined
})

// 加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分组数据
const groups = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = ref({
  id: undefined,
  groupId: undefined,
  name: '',
  url: '',
  icon: '',
  linkDesc: '',
  sortNo: 10,
  status: 1
})

// 自定义 SVG 验证规则
const validateIcon = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入SVG图标代码'))
  } else if (!validateSvg(value)) {
    callback(new Error('请输入有效的SVG图标代码'))
  } else {
    callback()
  }
}

// 表单校验规则
const rules = {
  groupId: [{ required: true, message: '请选择分组', trigger: 'change' }],
  name: [{ required: true, message: '请输入链接标题', trigger: 'blur' }],
  url: [{ required: true, message: '请输入链接地址', trigger: 'blur' }],
  icon: [
    { required: true, message: '请输入SVG图标代码', trigger: 'blur' },
    { validator: validateIcon, trigger: 'blur' }
  ],
  sortNo: [{ required: true, message: '请输入排序号', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 重置表单
const resetForm = () => {
  form.value = {
    id: undefined,
    groupId: undefined,
    name: '',
    url: '',
    icon: '',
    linkDesc: '',
    sortNo: 10,
    status: 1
  }
}

// 获取分组列表
const getGroups = async () => {
  try {
    const res = await request('/api/nav/group/list')
    if (res.code === 200) {
      groups.value = res.data
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
  }
}

// 获取链接列表
const getList = async () => {
  loading.value = true
  try {
    const res = await request('/api/nav/link/list', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        current: pageNum.value,
        size: pageSize.value,
        groupId: searchForm.groupId || undefined
      })
    })
    if (res.code === 200) {
      tableData.value = res.data.records || []
      total.value = Number(res.data.total) || 0
    } else {
      ElMessage.error(res.msg || '获取链接列表失败')
    }
  } catch (error) {
    console.error('获取链接列表失败:', error)
    ElMessage.error('获取链接列表失败')
  } finally {
    loading.value = false
  }
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '新增链接'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑链接'
  form.value = { ...row }
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该链接吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await request(`/api/nav/link/delete?id=${row.id}`, {
        method: 'GET'
      })
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 清理 SVG 代码
    const formData = { ...form.value }
    formData.icon = sanitizeSvg(formData.icon)
    
    const url = formData.id ? '/api/nav/link/update' : '/api/nav/link/add'
    const res = await request(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData)
    })
    
    if (res.code === 200) {
      ElMessage.success(formData.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      getList()
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  getList()
}

// 切换分组
const handleGroupChange = async (row, groupId) => {
  try {
    const res = await request('/api/nav/link/update', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...row, groupId })
    })
    
    if (res.code === 200) {
      ElMessage.success('更新成功')
      getList()
    } else {
      ElMessage.error(res.msg || '更新失败')
      // 更新失败时恢复原值
      row.groupId = row._oldGroupId
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
    // 更新失败时恢复原值
    row.groupId = row._oldGroupId
  }
}

// 修改 Radio 组件的使用方式
const handleStatusChange = (value) => {
  form.value.status = Number(value)
}

// 初始化
onMounted(() => {
  getGroups()
  getList()
})
</script>

<style scoped>
.nav-link {
  padding: 20px;
}
.search-card {
  margin-bottom: 20px;
}
.table-card {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.el-select-dropdown__item {
  display: block;
}
.icon-preview {
  margin-top: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.svg-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.svg-icon :deep(svg) {
  width: 1em;
  height: 1em;
  font-size: 20px;
}
</style> 